import Parser = require('tree-sitter');
import JavaScript from 'tree-sitter-javascript';
import Python from 'tree-sitter-python';
import Java from 'tree-sitter-java';
import Cpp from 'tree-sitter-cpp';
import Go from 'tree-sitter-go';
import Rust from 'tree-sitter-rust';

// 语言映射表
const LANGUAGE_MAP: Record<string, any> = {
  javascript: JavaScript,
  typescript: JavaScript,
  python: Python,
  java: Java,
  cpp: Cpp,
  c: Cpp,
  go: Go,
  rust: Rust,
};

export class LanguageManager {
  private parsers: Map<string, Parser> = new Map();

  getParser(languageId: string): Parser | null {
    // console.log(`[DEBUG] Requesting parser for: ${languageId}`);
    const LangParser = LANGUAGE_MAP[languageId];
    if (!LangParser) 
      {
        console.error(`[ERROR] Unsupported language: ${languageId}`);
        return null;
      }
    // 重用已创建的解析器
    if (this.parsers.has(languageId)) {
      return this.parsers.get(languageId)!;
    }

    // 创建新的解析器
    const parser = new Parser();
    parser.setLanguage(LangParser);
    this.parsers.set(languageId, parser);
    return parser;
  }

  isSupported(languageId: string): boolean {
    return languageId in LANGUAGE_MAP;
  }
}